<?php
namespace Admin\Controller;
use Common\Controller\BaseController;

class PublicController extends BaseController{     
	public function index(){
		$ip = get_client_ip();
		if(IS_POST){
			$yzImg = I('post.yzImg');
			if(strlen($yzImg) == 0){
				$this->returnResult(false, '验证码不能为空');
			}
			$authnum=I('session.login_check_number');
			if($yzImg != $authnum){
				$this->returnResult(false, '验证码不正确');
			}
			$name = I('post.username');
			$pwd = I('post.password');
			$info = M('admins')->field('*')->where(array('status' => 1, 'gh' => $name))->find();
			if($info['pwd'] === md5($name . '_NiU_' . $pwd)){
				$rules = M('group')->where(array('id' => $info['gid']))->getField('rules');
				$_adminInfo = $info;
				unset($_adminInfo['id']);
				unset($_adminInfo['remark']);
				unset($_adminInfo['last_login_time']);
				unset($_adminInfo['last_login_ip']);
				$info['rules'] = $rules;
				session('adminInfo', $info);
				M('admins')->where(array('id' => $info['id']))->save(array('last_login_time' => time(), 'last_login_ip' => $ip));
				M('admin_login_log')->add(array('name' => $name, 'times' => time(), 'ip' => $ip));
				
				$this->returnResult(true,'登录成功', U('Index/index'));			
			}else{
				M('admin_login_log')->add(array('name' => $name, 'times' => time(), 'ip' => $ip, 'status' => 0, 'pwd' => $pwd));
               
				$this->returnResult(false, '账号或密码错误');
			}

		}else{
			if(session('adminInfo.id') > 0){
				$this->redirect('Admin/Index/index');
			}
			$this->display(C("LoginPage"));
		}
	}

	public function logout(){
		session('[destroy]');
		$this->redirect('Admin/Public/index');
	}

	public function editPwd(){
		if(IS_POST){
			$pwd = M('admins')->where(array('id' => session('adminInfo.id')))->getField('pwd');
			if(md5(session('adminInfo.name') . '_NiU_' . I('post.old_pwd')) === $pwd){
				$data['id'] = session('adminInfo.id');
				$data['pwd'] = md5(session('adminInfo.gh') . '_NiU_' . I('post.new_pwd'));
				$result = $this->updateData($data, 'admins', 2);
				$this->returnResult($result, null, U('Index/index'));
			}
			$this->returnResult(false, '原始密码错误');
		}else{
			$this->assign('menuList', session('left_menu'));
			$this->display();
		}
	}
}